package com.settlement.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.common.util.DateUtils;
import com.settlement.system.mapper.TbBillMapper;
import com.settlement.system.model.entity.SysPlatform;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.entity.TbBill;
import com.settlement.system.model.query.TbBillPageQuery;
import com.settlement.system.model.vo.TbBillImportVo;
import com.settlement.system.service.TbBillService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 淘宝账单 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2023-08-05
 */
@Service
@RequiredArgsConstructor
public class TbBillServiceImpl extends ServiceImpl<TbBillMapper, TbBill> implements TbBillService {

    @Override
    public Page<TbBill> getTbBillPage(TbBillPageQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 查询数据
        String tableName = "tb_bill_%s".formatted(queryParams.getBillMonth());
        queryParams.setTableName(tableName);
        if (!StringUtils.hasText(this.baseMapper.existTable(tableName))) {
            return new Page<>(pageNum, pageSize);
        }
        Page<TbBill> page = new Page<>(pageNum, pageSize);
        return this.baseMapper.getPage(page, queryParams);
    }

    @Override
    public void addImportData(List<TbBillImportVo> vos, SysStore sysStore, SysPlatform sysPlatform, Map<String, String> linkNoMap) {
        List<String> billMonthList = new ArrayList<>();
        for (TbBillImportVo vo : vos) {
            if (vo.getSettlementTime() != null) {
                String billMonth = DateUtils.formatDate(vo.getSettlementTime());
                if (!billMonthList.contains(billMonth)) {
                    billMonthList.add(billMonth);
                }
            }
        }
        // 需要新增的列表
        List<TbBillImportVo> createVos = new ArrayList<>();
        // 需要更新的列表
        List<TbBillImportVo> updateVos = new ArrayList<>();
        List<String> orderNos = vos.stream().map(TbBillImportVo::getSellerNo).filter(StringUtils::hasText).toList();
        // 根据订单号找到所有历史记录
        List<TbBill> list = new ArrayList<>();
        for (String billMonth : billMonthList) {
            TbBillPageQuery pageQuery = new TbBillPageQuery();
            pageQuery.setSellerNos(orderNos);
            pageQuery.setTableName("tb_bill_%s".formatted(billMonth));
            // 根据账单日期查询对应表的核销数据
            List<TbBill> tbBillList = this.baseMapper.getList(pageQuery);
            if (tbBillList != null && tbBillList.size() > 0) {
                list.addAll(tbBillList);
            }
        }
        for (TbBillImportVo vo : vos) {
            TbBill bill = list.stream().filter(tbBill -> tbBill.getSellerNo().equals(vo.getSellerNo())).findFirst().orElse(null);
            if (bill == null) {
                // 加入到新增的列表
                createVos.add(vo);
            } else {
                // 加入到更新的列表
                updateVos.add(vo);
            }
        }
        List<String> columnList = TbBill.getDateColumn();
        columnList.add("id");
        for (TbBillImportVo updateVo : updateVos) {
            list.stream().filter(tbBill -> tbBill.getSellerNo().equals(updateVo.getSellerNo())).findFirst().ifPresent(tbBill -> {
                BeanUtil.copyProperties(updateVo, tbBill, columnList.toArray(new String[0]));
                tbBill.setUpdateTime(LocalDateTime.now());
                tbBill.setTableName("tb_bill_%s".formatted(DateUtils.formatDate(tbBill.getSettlementTime())));
                this.baseMapper.update(tbBill);
            });
        }
        for (TbBillImportVo vo : createVos) {
            TbBill tbBill = new TbBill();
            BeanUtil.copyProperties(vo, tbBill, columnList.toArray(new String[0]));
            tbBill.setCreateTime(LocalDateTime.now());
            tbBill.setUpdateTime(LocalDateTime.now());
            tbBill.setTableName("tb_bill_%s".formatted(DateUtils.formatDate(tbBill.getSettlementTime())));
            tbBill.setPlatform(sysPlatform.getPlatformKey());
            tbBill.setStoreId(sysStore.getId());
            tbBill.setStoreName(sysStore.getCommercePlatformStoreName());
            tbBill.setAuditNo(linkNoMap.get(tbBill.getSellerNo()));
            tbBill.setBillMonth(linkNoMap.get(tbBill.getSellerNo() + "账单月份"));
            // 判断历史表是否存在，不存在则新增
            if (!StringUtils.hasText(this.baseMapper.existTable(tbBill.getTableName()))) {
                this.createTable(tbBill.getTableName());
            }
            this.baseMapper.insertData(tbBill);
        }
    }

    @Override
    public boolean createTable(String tableName) {
        return this.getBaseMapper().createTable(tableName) > 0;
    }

    @Override
    public List<TbBill> getList(TbBillPageQuery queryParams) {
        return this.getList(queryParams);
    }
}
